package com.zhangzeqin.code.dao.Impl;

import com.zhangzeqin.code.dao.TimeDao;
import com.zhangzeqin.code.entity.Time;
import com.zhangzeqin.code.entity.User;
import com.zhangzeqin.code.util.DruidTool;
import com.zhangzeqin.code.util.JdbcUtil;
import com.zhangzeqin.code.view.LearnWordView;
import com.zhangzeqin.code.view.LoginHandler;
import com.zhangzeqin.code.view.LoginView;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;


public class TimeDaoImpl implements TimeDao {
    @Override
    public double getTime() throws SQLException {
        //获取登录用户的账号  LoginHandler.user
      String sql="select studyTime from user where name='"+ LoginHandler.user+"';";
        //获取连接
        Connection connection = DruidTool.getConnection();

        //创建预编译statement
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        //返回结果集
        ResultSet resultSet = preparedStatement.executeQuery(sql);

        double studyTime=0;
        while(resultSet.next()) {
             studyTime = (double) resultSet.getObject(1);
        }
        if (resultSet.next()){
            //是否收回连接,需要考虑是不是事务
            if(connection.getAutoCommit()){
                //没有开启事务,正常回收连接
                DruidTool.recycleConnection(connection);
            }
            resultSet.close();
        }
        return studyTime;
    }



    @Override
    public boolean updateTime(long startTime,long endTime) {
        String sql="update user set studyTime=? where name='"+LoginHandler.user+"';";


        //创建Time实现接口类的对象获取启动时间
        TimeDao timeDao=new TimeDaoImpl();

        Double hour = new BigDecimal((float) (endTime-startTime) / (1000*60*60  ))
                .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        //最后转为int整形
        double totalTime=0;
        int i=0;
        try {
             totalTime=(double)(hour+timeDao.getTime());
            System.out.println(hour);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        //连接数据库
        try {
            i = JdbcUtil.executeUpdate(sql,totalTime);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if(i!=0){
            return true;
        }
        return false;

    }
}
